package com.itzdm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzdm.reggie.common.Result.Result;
import com.itzdm.reggie.common.basecontext.BaseContext;
import com.itzdm.reggie.dto.OrdersDto;
import com.itzdm.reggie.entity.*;
import com.itzdm.reggie.mapper.OrderMapper;
import com.itzdm.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    
    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;
    @Override
    public void submit(Orders order) {
        //查询用户ID
        Long id = BaseContext.getCurrentId();
        //查询用户购物车
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, id);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        if (list == null || list.isEmpty()) {
            throw new RuntimeException("购物车为空");
        }
        //查询用户数据
        User user = userService.getById(id);
        long id1 = IdWorker.getId();
        //查询地址信息
        Long addressBookId = order.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new RuntimeException("用户地址为空");
        }
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetailList = list.stream().map(item->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).toList();
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setStatus(2);
        order.setAmount(new BigDecimal(amount.get())); //总金额
        order.setUserId(id);
        order.setUserName(user.getName());
        order.setConsignee(addressBook.getConsignee());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setNumber(String.valueOf(id1));
        save(order);
        //向订单表中插入数据
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setOrderId(order.getId());
        }
        //订单明细插入数据
        orderDetailService.saveBatch(orderDetailList);

        //清空购物车
        shoppingCartService.remove(wrapper);
    }

    @Override
    public Page pageOrder(int page, int pageSize) {
        //获取当前用户ID
        Long currentId = BaseContext.getCurrentId();
        //构造分页查询
        Page<Orders> orderPage = new Page<>(page, pageSize);
        Page<OrdersDto> p = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        //查询当前用户所有顶单
        wrapper.eq(Orders::getUserId, currentId);
        //根据订单时间排序
        wrapper.orderByDesc(Orders::getOrderTime);
        //进项条件分页查询，赋值给orderPage
        page(orderPage,wrapper);
        //仅复制除了记录的其他属性
        BeanUtils.copyProperties(orderPage,p,"records");
        List<Orders> records = orderPage.getRecords();
        List<OrdersDto> list = records.stream().map(item->{
            OrdersDto ordersDto = new OrdersDto();
            //获取orderId查询orderDetail中数据
            Long orderId = item.getId();
            //条件构造器
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> details = orderDetailService.list(lambdaQueryWrapper);
            //拷贝属性
            BeanUtils.copyProperties(item,ordersDto);
            ordersDto.setOrderDetails(details);
            return ordersDto;
        }).toList();
        //将处理的detail数据set
        p.setRecords(list);
        return p;
    }

    @Override
    public Page OrderPage(int page, int pageSize, Long number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrdersDto>  ordersDtoPage= new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);
        wrapper.like(number!= null,Orders::getNumber,number);
        wrapper.gt(beginTime != null,Orders::getOrderTime,beginTime)
                .lt(endTime != null,Orders::getOrderTime,endTime);
        page(ordersPage,wrapper);
        BeanUtils.copyProperties(ordersDtoPage,ordersPage,"records");
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> details = orderDetailService.list(lambdaQueryWrapper);
            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setOrderDetails(details);
            return ordersDto;
        }).toList();
        ordersDtoPage.setRecords(ordersDtoList);
        return ordersPage;
    }

    @Override
    public void again(Orders order) {
        Long orderId = order.getId();
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
        List<OrderDetail> details = orderDetailService.list(lambdaQueryWrapper);

        //获取当前用户ID
        Long currentId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = details.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart);
            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).toList();
        shoppingCartService.saveBatch(shoppingCartList);
    }
}
